package grouplife::Controller::QQLogin;
use Moose;
use Encode;
use namespace::autoclean;
use Catalyst qw/
Session
Session::Store::FastMmap
Session::State::Cookie
/;
use Util::Renren::Authenticate;
use Util::QQ::QQAuthenticate;
use grouplife::Model::Store::StoreSearchModel;
use grouplife::Model::Users::UsersSearchModel;
use grouplife::Model::Users::UserRegisterModel;
use grouplife::Model::CommentedItem::CommentedItemModel;
use Util::Email::SendEmail;
use Time::Piece;

BEGIN {extends 'Catalyst::Controller'; }
__PACKAGE__->config( 'Plugin::ConfigLoader' => { file => 'grouplife.yml' } );

=head1 NAME

grouplife::Controller::Login - Catalyst Controller

=head1 DESCRIPTION

Catalyst Controller.

=head1 METHODS

=cut


=head2 index

=cut


sub index :Path :Args(0) {
	my ($self, $c) = @_;

# Get the username and password from form
	my $code = $c->request->params->{code} || '0';
	my $openId;
	my $nickName;	
	my $authenticator = Util::QQ::QQAuthenticate->new();
	my $qq_app_id = $c->config->{qq_app_id};
	my $qq_app_key = $c->config->{qq_app_key};
	my $qq_redirect_url = $c->config->{qq_redirect_uri};
	my $qq_auth_access = $c->config->{qq_auth_access};
	my $qq_auth_openid = $c->config->{qq_auth_openid};
	my $qq_auth_userinfo = $c->config->{qq_auth_userinfo};
	my $user = $authenticator->get_userinfo($code, $qq_auth_access,$qq_app_id, $qq_app_key, $qq_redirect_url);
	if($user->{code} == 0) {
		my $user1 = $authenticator->get_openId($user->{access_token}, $qq_auth_openid);
		if($user1->{code} == 0) {
			$openId = $user1->{openId};
			my $user2 = $authenticator->get_nick_name($user->{access_token}, $openId, $qq_app_id, $qq_auth_userinfo);
			if($user2->{code} == 0) {
				$nickName = $user2->{nickName};
			}
			$nickName = encode_utf8($nickName);
			my $source_nick = $nickName . "|" . $openId;
			my $users = $c->model('Users::UsersSearchModel')->renren_get_user_by_nick(3,$source_nick);
			my $length = scalar(@$users);
			if ($length == 0) {
				$c->stash(nick  =>  $nickName);
				$c->stash(openId  =>  $openId);
				$c->stash(source_nick => $source_nick);
				$c->stash(css => 'zhuce.css');
				$c->stash(javascript => '/user/form_create.js');
        			$c->stash(title => 'QQ账号绑定');
				$c->stash(template => 'qq/qq_bind.tt2');
				return 0;
			} else {
				my $auth_user = $c->find_user({ id => $users->[0]->id });
				$c->set_authenticated($auth_user);
				$c->session->{login_user} = $auth_user;
				$c->response->redirect($c->uri_for($c->controller('Users')->action_for('user_info'), [$users->[0]->id]));
				return 0;
			}
		}
	}
	$c->stash(css => 'zhuce.css');
	$c->stash(title => 'QQ登录失败');
	$c->stash(template => 'qq/qq_bind_failure.tt2');
}

=head1 AUTHOR

lijie,,,

=head1 LICENSE

This library is free software. You can redistribute it and/or modify
it under the same terms as Perl itself.

=cut

__PACKAGE__->meta->make_immutable;

1;
